﻿package net.wangit.util;

import java.util.Random;

public class RandomUtil {

	private static Random RANDOM = new Random();
	private static char CHARACTERS[];
	private static int CHARACTER_BOUND;
	private static char INTEGER_CHARACTERS[];
	private static int INTEGER_CHARACTERS_BOUND;

	public RandomUtil() {
	}

	public static String getRandomString(int length) {
		if (length < 1)
			return "";
		StringBuffer sb = new StringBuffer(length);
		for (int i = 0; i < length; i++)
			sb.append(CHARACTERS[RANDOM.nextInt(CHARACTER_BOUND)]);

		return sb.toString();
	}

	public static int getRandomInteger(int length) {
		if (length < 1 || length > 9)
			return 0;
		StringBuffer sb = new StringBuffer(length);
		for (int i = 0; i < length; i++)
			sb.append(INTEGER_CHARACTERS[RANDOM
					.nextInt(INTEGER_CHARACTERS_BOUND)]);

		return Integer.parseInt(sb.toString());
	}

	public static String getRandomIntegerString(int length) {
		return Integer.toString(getRandomInteger(length));
	}

	public static double getRandomDouble(int length, int scale) {
		if (length < 1 || scale < 1)
			return 0.0D;
		StringBuffer sb = new StringBuffer(length);
		for (int i = 0; i < length; i++)
			sb.append(INTEGER_CHARACTERS[RANDOM
					.nextInt(INTEGER_CHARACTERS_BOUND)]);

		sb.append(".");
		for (int i = 0; i < scale; i++)
			sb.append(INTEGER_CHARACTERS[RANDOM
					.nextInt(INTEGER_CHARACTERS_BOUND)]);

		return Double.parseDouble(sb.toString());
	}

	public static String getRandomDoubleString(int length, int scale) {
		return Double.toString(getRandomDouble(length, scale));
	}

	static {
		CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
				.toCharArray();
		CHARACTER_BOUND = CHARACTERS.length - 1;
		INTEGER_CHARACTERS = "01234506789".toCharArray();
		INTEGER_CHARACTERS_BOUND = INTEGER_CHARACTERS.length - 1;
	}
}
